package com.sz.zhiling.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sz.zhiling.common.HttpClientUtils;
import com.sz.zhiling.common.TokenUtils;
import com.sz.zhiling.entity.Fans;
import com.sz.zhiling.mapper.FansMapper;
import com.sz.zhiling.service.FansService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FansServiceImpl implements FansService {
    //将通用接口注入
    @Autowired
    private FansMapper fansMapper;
    //将得到token注入
      @Autowired
     private TokenUtils utils;
      //得到所有关注的粉丝
    @Override
    public String getAllFans() {
        String url="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+utils.getToken()+"&next_openid=";
         String result=HttpClientUtils.getMethod(url);
        JSONObject json=JSON.parseObject(result);
        String data = json.get("data").toString();
        JSONObject openid=JSON.parseObject(data);
       String userdata= openid.get("openid").toString();
        System.out.println("所有粉丝的信息:"+userdata);
        List<String> list = JSON.parseArray(userdata,String.class);
        for (String s : list) {
            String f=getFansDetails(s);
            Fans fans = JSON.parseObject(f,Fans.class);
            saveFans(fans);
            //sendMessage(s);
        }
        return result;
    }
    //获得每个粉丝的详细信息
    @Override
    public String getFansDetails(String openid) {
        String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+utils.getToken()+"&openid="+openid+"&lang=zh_CN";
        String result=HttpClientUtils.getMethod(url);
        System.out.println("用户的信息为"+result);
        return result;
    }
   //给每位粉丝发送消息
    @Override
    public String sendMessage(String openid) {
        String url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+utils.getToken();
        String json="{\n" +
            "    \"touser\":\""+openid+"\",\n" +
                    "    \"msgtype\":\"text\",\n" +
                    "    \"text\":\n" +
                    "    {\n" +
                    "         \"content\":\"你好啊，在上路\"\n" +
                    "    }\n" +
                    "}";
        String result=HttpClientUtils.postMethod(url,json);
        System.out.println("发送的信息为:"+result);
        return result;
    }
   //将每一位粉丝的信息存入数据库
    @Override
    public String saveFans(Fans fans) {
        int n=fansMapper.insertSelective(fans);
        String msg=n>0?"保存成功":"保存失败";
        return msg;
    }
    //从数据库查找粉丝信息
    @Override
    public List<Fans> findAllFans() {
        return fansMapper.selectAll();
    }
}
